#!/usr/bin/perl

#input1 delay/loss table
#output1 <average loss rate, mean delay, std delay, jitter> maybe interframe gap mean, std, even seq later
#output2 to store all results into one file, used for plotting (diff sending rate)

open(INPUT1, $ARGV[0]) or die "$ARGV[0] cannot be opened.\n";
open(OUTPUT1, ">$ARGV[1]") or die "$ARGV[1] cannot be created.\n";
#open(OUTPUT2, ">$ARGV[2]") or die "$ARGV[2] cannot be created.\n";
#open(OUTPUT3, ">>$ARGV[3]") or die "$ARGV[3] cannot be created.\n";

$loss_counter=0;
$delay_counter=0;
$counter=0;
$sum_delay=0;
$var_delay=0;
$std_delay=0;
$jitter=0;
$jitter_total=0;
$square_sum_delay=0;
$gap=0;
$sum_gap=0; 
$square_sum_gap=0;

$is_first_delay=0; #for jitter calculation
$is_first_packet=0;

while($line = <INPUT1>)
{
	chomp($line);
	@block=split(', ', $line);
	$flow_num = $block[0];
	$seq_num = $block[1];
	$arrival_ts = $block[2];
	$delay = $block[3];
	$total_seq_num = $block[4];

	#print ("flow_num = $flow_num, seq_num = $seq_num; arrival_ts = $arrival_ts, delay = $delay, total_seq_num = $total_seq_num\n");
	$counter++;
	
	if($delay == 0)
	{
		$loss_counter++;
	}
	else
	{
		$delay_counter++;
		$sum_delay += $delay;
		$square_sum_delay += $delay**2;
		
		if($is_first_delay==0)
		{
			$is_first_delay=1;			
		}
		else
		{
			$jitter_total += abs($delay-$pre_delay);
		}
        	$pre_delay = $delay;

		if($is_first_packet==0)
		{
			$is_first_packet=1;
		}
		else
		{
			$gap=($arrival_ts-$pre_arrival_ts)*(10**6);
			$sum_gap += $gap;
			$square_sum_gap += $gap**2;
		}
		$pre_arrival_ts = $arrival_ts;
	}	
}

$loss_rate = $loss_counter/$counter;

$mean_delay = $sum_delay/$delay_counter;
$autocor_delay = $square_sum_delay/$delay_counter;
$var_delay = $autocor_delay-$mean_delay**2;
$std_delay = sqrt($var_delay);

$jitter = $jitter_total/($delay_counter-1);

$mean_gap = $sum_gap/($delay_counter-1);
$autocor_gap = $square_sum_gap/($delay_counter-1);
$var_gap = $autocor_gap-$mean_gap**2;
$std_gap = sqrt($var_gap);

$formatted_mean_delay=sprintf("%.3f", $mean_delay);
$formatted_std_delay=sprintf("%.3f", $std_delay);
$formatted_jitter=sprintf("%.3f", $jitter);
$formatted_mean_gap=sprintf("%.3f", $mean_gap);
$formatted_std_gap=sprintf("%.3f", $std_gap);

print OUTPUT1 "$loss_rate, $formatted_mean_delay, $formatted_std_delay, $formatted_jitter, $formatted_mean_gap, $formatted_std_gap\n";


close(INPUT1);
#close(INPUT2);
close(OUTPUT1);
